package com.szalay.desktopsearch.indexer;

import java.io.File;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Checks the solr index and removes non-existing files.
 * @author szalay
 */
public class DeleteTask implements StatefulJob {
    /** Logger. */
    private final static Logger logger = LoggerFactory.getLogger(IndexingTask.class);
    
    /** Solr. */
    private SolrServer solr;
    
    @Override
    public void execute(JobExecutionContext jec) throws JobExecutionException {
        solr = (SolrServer) jec.getJobDetail().getJobDataMap().get(SolrServer.class.getName());
        
        //Query all documents
        final SolrQuery query = new SolrQuery();
        query.setFields(Fields.PATH);
        query.setQuery("*:*");
        query.setRows(Integer.MAX_VALUE);
       
        try {
            boolean changed = false;
            final QueryResponse allDocuments = solr.query(query);
            final SolrDocumentList results = allDocuments.getResults();
            for (final SolrDocument doc : results) {
                final String path = (String) doc.getFieldValue(Fields.PATH);
                final File file = new File(path);
                if (!file.exists()) {
                    //The file does not exist, delete it
                    solr.deleteById(path);
                    changed = true;
                }
            }
             
            //Commit and optimize
            if (changed) {
                solr.optimize();
                solr.commit();
            }
        } catch(Exception ex) {
            logger.warn(null, ex);
        } 
    }
    
}
